package com._101aiot.web.loginuser.handler;


import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONObject;
import com._101aiot.web.loginuser.api.UserDTO;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
public class LoginUserHolder {

    public UserDTO getCurrentUser(){
        //从Header中获取用户信息
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert servletRequestAttributes != null;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String userStr = request.getHeader("user");
        JSONObject userJsonObject = new JSONObject(userStr);

        // 未经过gateway，调用用户登录信息会报错， 额外处理，增加判断是否经过网关，如果没经过，

        UserDTO userDTO = new UserDTO();
        userDTO.setUsername(userJsonObject.get("user_name").toString());
        userDTO.setId(Convert.toLong(userJsonObject.get("id")));
        userDTO.setRoles(Convert.toList(String.class,userJsonObject.get("authorities")));
        return userDTO;
    }
}
